package com.jy.appmarket.utils;

import android.text.TextUtils;

public class AppLinkParser {
	private static final String TAG = AppLinkParser.class.getSimpleName();
	public static final String SCHEMA = "jy-market-app://";

	private String uriString;
	private String pkgName;
	private String dlUrl;
	private String name;
	private String versionName;
	private int versionCode;
	private String iconUrl;
	private String source;
	private String md5;

	public AppLinkParser(String uri) {
		uriString = uri;
		init();
	}

	public boolean isValid() {
		return !TextUtils.isEmpty(pkgName) && !TextUtils.isEmpty(dlUrl) && !TextUtils.isEmpty(name);
	}

	public boolean isValidStrict() {
		return isValid() && !TextUtils.isEmpty(versionName) && !TextUtils.isEmpty(iconUrl)
				&& !TextUtils.isEmpty(source) && !TextUtils.isEmpty(md5);
	}

	private void init() {
		if (uriString == null || !uriString.startsWith(SCHEMA)) {
			return;
		}
		String tmp = uriString.substring(SCHEMA.length());
		int i = tmp.indexOf("?");
		if (i < 0) {
			pkgName = tmp;
			return;
		}
		pkgName = tmp.substring(0, i);

		tmp = tmp.substring(i + 1);

		if (tmp == null || tmp.isEmpty()) {
			return;
		}
		String[] ss = tmp.split("&");
		if (ss == null) {
			return;
		}
		for (String param : ss) {
			String[] kv = param.split("=");
			if (kv == null || kv.length == 0) {
				continue;
			}
			String k = NetTools.urlDecode(kv[0]);
			if (TextUtils.isEmpty(k)) {
				continue;
			}

			String v = "";
			if (kv.length > 1) {
				v = NetTools.urlDecode(kv[1]);
			}
			setParams(k, v);
		}
	}

	private void setParams(String k, String v) {
		if ("dlUrl".equals(k)) {
			dlUrl = v;
		} else if ("name".equals(k)) {
			name = v;
		} else if ("versionName".equals(k)) {
			versionName = v;
		} else if ("versionCode".equals(k)) {
			try {
				versionCode = Integer.valueOf(v);
			} catch (Exception e) {
				// ignore
			}
		} else if ("iconUrl".equals(k)) {
			iconUrl = v;

		} else if ("source".equals(k)) {
			source = v;
		} else if ("md5".equals(k)) {
			md5 = v;
		} else {
			LogUtil.w(TAG, "unsupported param:" + k);
		}
	}

	public String getPkgName() {
		return pkgName;
	}

	public String getDlUrl() {
		return dlUrl;
	}

	public String getName() {
		return name;
	}

	public String getVersionName() {
		return versionName;
	}

	public int getVersionCode() {
		return versionCode;
	}

	public String getIconUrl() {
		return iconUrl;
	}

	public String getSource() {
		return source;
	}

	public String getMd5() {
		return md5;
	}

}